# -*- coding: utf-8 -*-
# =============================================================================
#     FileName:
#         Desc:
#       Author:
#        Email:
#     HomePage:
#      Version:
#   LastChange:
#      History:
# =============================================================================
from utils.log_helper import LogHelper
from utils.mysql_server import MySQLServer

logger = LogHelper.get_logger()


class TargetServer(object):
    def __init__(self, mysql_server: MySQLServer, table_name, batch_insert_rows=100):
        self.mysql_server = mysql_server
        self.database_name = mysql_server.database_name
        self.batch_insert_rows = batch_insert_rows
        self.table_name = table_name
        self.primary_key_name = ""
        self.primary_key_type = ""

    def get_table_columns(self):
        sql_script = """ DESC `{database_name}`.`{table_name}` """.format(
            database_name=self.mysql_server.database_name,
            table_name=self.table_name
        )
        query_result = self.mysql_server.mysql_query(sql_script=sql_script, return_dict=True)
        return query_result

    def delete_data_by_keys(self, key_items):
        if len(key_items) == 0:
            return 0
        where_keys = ",".join(list(map(lambda key: "%s", key_items)))
        sql_script = """
DELETE FROM `{database_name}`.`{table_name}` 
WHERE `{primary_key_name}` IN ({where_keys});
""".format(
            database_name=self.mysql_server.database_name,
            table_name=self.table_name,
            primary_key_name=self.primary_key_name,
            where_keys=where_keys
        )
        affect_rows = self.mysql_server.mysql_exec(
            sql_script=sql_script,
            sql_paras=key_items
        )
        logger.info("在目标实例上清理记录: {}".format(affect_rows))
        return affect_rows

    def check_data_by_keys(self, key_items):
        if len(key_items) == 0:
            logger.info("满足条件的主键记录数为0，无需对目标表进行数据检查")
            return True
        where_keys = ",".join(list(map(lambda key: "%s", key_items)))
        sql_script = """
SELECT COUNT(1) AS rows_count FROM `{database_name}`.`{table_name}` 
WHERE `{table_primary_key}` IN ({where_keys});
""".format(
            database_name=self.database_name,
            table_name=self.table_name,
            table_primary_key=self.primary_key_name,
            where_keys=where_keys
        )
        query_result = self.mysql_server.mysql_query(
            sql_script=sql_script,
            sql_paras=key_items,
            return_dict=True
        )
        if query_result[0]["rows_count"] == len(key_items):
            logger.info("在目标实例上插入记录: {}(期望)/{}(实际)=正常".format(
                len(key_items),
                query_result[0]["rows_count"],
            ))
            return True
        else:
            logger.warning("在目标实例上插入记录: {}(期望)/{}(实际)=异常".format(
                len(key_items),
                query_result[0]["rows_count"],
            ))
            logger.warning("涉及KEY: {}".format(
                ",".join(list(map(lambda key: str(key), key_items)))
            ))
            return False

    def insert_row_items(self, row_items):
        affect_rows = self.mysql_server.insert_multi_rows(
            database_name=self.database_name,
            table_name=self.table_name,
            row_items=row_items
        )
        logger.info("在目标实例上插入记录: {}".format(affect_rows))

    def is_table_exist(self):
        sql_script = """
SELECT * 
FROM information_schema.tables
WHERE TABLE_SCHEMA=%s
AND TABLE_NAME=%s;
"""
        query_result = self.mysql_server.mysql_query(
            sql_script=sql_script,
            sql_paras=[self.database_name, self.table_name],
            return_dict=False
        )
        if len(query_result) > 0:
            return True
        else:
            return False
